from flask import *
import MySQLdb

app = Flask(__name__)

#用户信息
account = []

#获得所有用户
db = MySQLdb.connect("localhost", "root", "123456", "mymonitor", charset='utf8')
cursor = db.cursor()
sql = "SELECT * FROM account"
try:
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
        account.append([row[0], row[1]])
except Exception as e:
    print(str(e))
cursor.close()
db.close()

#查找用户
def findAccount(username, password):
    for i in range(len(account)):
        if((account[i][0] == username) and (account[i][1] == password)):
            return i
    return -1

#新增用户
def addAccount(username, password):
    db = MySQLdb.connect("localhost", "root", "123456", "mymonitor", charset='utf8')
    cursor = db.cursor()
    sql = "INSERT INTO account(username, password) " \
          "VALUES ('%s', '%s')" % \
          (username, password)
    try:
        cursor.execute(sql)
        db.commit()
        account.append([username, password])
        flag = 1
    except Exception as e:
        print(str(e))
        flag = 0
    cursor.close()
    db.close()
    return flag

#欢迎界面
@app.route('/')
def index():
    return render_template('index.html')

#登录页面
@app.route('/login', methods=['GET', 'POST'])
def loginForm():
    if (request.method == 'GET'):
        return render_template('login.html')

#主页面
@app.route('/main')
def mainForm():
    return render_template('main.html')

#个人信息页面
@app.route('/info')
def infoForm():
    return render_template('user-info.html')

#用户管理页面
@app.route('/management')
def managementForm():
    return render_template('user-management.html')

#数据报告页面
@app.route('/charts')
def chartsForm():
    return render_template('charts.html')

#监控管理页面
@app.route('/video')
def videoForm():
    return render_template('video.html')

#报寝管理页面
@app.route('/register')
def registerForm():
    return render_template('register-management.html')

#日程管理页面
@app.route('/schedule')
def scheduleForm():
    return render_template('schedule.html')

#待开发页面
@app.route('/developing')
def developingForm():
    return render_template('developing.html')

#登录功能
@app.route('/main', methods=['GET', 'POST'])
def login():
    if(request.method == 'POST'):
        username = request.form.get('username')
        password = request.form.get('password')
        if(findAccount(username, password) != -1):
            return render_template('main.html')
        return '用户名或密码错误'

#退出
@app.route('/login')
def quit():
    return render_template('login.html')

if __name__ == '__main__':
    app.run()
